<template>
	<s-layout title="货源推荐" navbar="normal1">
		<!-- 导航栏 -->
    <assNavbar title="货源推荐">
      <template #right>
			
			</template>
    </assNavbar>
		<view class="distribution-index ss-p-x-20 ss-p-b-20">
			<su-fixed top :bgStyles="{background:'#F7F7F7'}" placeholder>
				<!-- 搜索栏 -->
				<view class="search-wrap" ref="searchRef">
					<view class="search" :style="{top: statusBarHeight + 'px'}">
						<view class="search-box">
							<input 
								type="text" 
								class="keyword ss-font-30 ss-p-x-20 ss-p-y-20 ss-radius-100" 
								@confirm="search" 
								v-model="storeParams.title"
								placeholder="可输入标题搜索" 
							/>
						</view>
					</view>
					<view @click="state.menuShow = true">
						<image 
							class="more-img ss-p-x-40 ss-p-y-18"
							:src="sheep.$url.cdn('/storage/default/20250418/08cdbcea0f1298fe262c86c14b735c7a.png')" 
						/>
					</view>
				</view>
			</su-fixed>
			<!-- 快速出单好货 -->
			<ProductSection
				:top-image="sheep.$url.cdn('/storage/default/20250418/6ab77725a486017b8b17b71236c54f91.png')"
				:show-top-title="true"
				:top-title-image="sheep.$url.cdn('/storage/default/20250418/db6ec78520ee2d874b9321ff98505889.png')"
				top-title-text="爆款趋势商品热卖中"
				:items="state.quickList"
				class="list-quick"
				@tap="handleProductClick('quick')"
			/>

			<view class="list-card2">
				<!-- 站外爆款热销 -->
				<ProductSection
					:top-image="sheep.$url.cdn('/storage/default/20250418/4e21ec66597153d6bbbf9bed4ee26084.png')"
					:items="state.hotList"
					class="list-hot"
					@tap="handleProductClick('hot')"
				/>

				<!-- 严选供货商 -->
				<ProductSection
					:top-image="sheep.$url.cdn('/storage/default/20250418/2c11ab5372266cf35f1ec5618278788a.png')"
					:items="state.supplierList"
					class="list-supplier"
					@tap="handleProductClick('supplier')"
				/>
			</view>

			
			<!-- 商品类目 -->
			<view class="cate-list" >
				<su-sticky bgColor="#F7F7F7" :offsetTop="50">

				<su-tabs 
					:list="state.tabs"  
					:scrollable="true" 
					:borderNode="state.borderNode" 
					lineHeight="0"
					backgroundColor="#F7F7F7"
					:current="state.currentTab" 
					:activeStyle="{color:'#1D1D1D','font-size':'36rpx',fontFamily: 'YouSheBiaoTiHei'}" 
					itemStyle="height:38rpx,padding: '20rpx 0'"
					:inactiveStyle="{'color':'6C6C6C','font-size':' 28rpx'}"
					@change="onTabsChange" 
					keyName='name'
				>
				</su-tabs>
			</su-sticky>
				<view class="tabs-content">
					<ProductCard class="product-card"
						v-for="(product, index) in state.products" 
						:key="index"
						:product="product"
						@action="handleProductAction"
					/>
					
					<s-empty class="w-100" v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无数据"></s-empty>
					<view class="w-100"  v-else >
						<uni-load-more :status="state.loadStatus"
							:content-text="{ contentdown: '点击或上拉加载更多', }" @tap="loadmore" />
					</view>
				</view>
			</view>
		</view>
		<fui-actionsheet 
			:show="state.showShort" 
			:itemList="showList" 
			@click="typeClick"
			@cancel="state.showShort = false">
		</fui-actionsheet>

		<!-- 弹框 -->
		<su-popup :show="state.menuShow" type="center" @close="state.menuShow = false">
			<view class="menu-box" >
				<view 
					class="menu-item" 
					v-for="item in state.menuList" 
					:key="item.id"
					@click="handleMenuClick(item.id)"
				>
					<view class="img">
						<image :src="item.image" mode=""></image>
					</view>
					<view class="title">{{item.name}}</view>
					
				</view>
			</view>
		</su-popup>
		<!-- 铺货成功的弹框 -->
		<su-popup :show="show" type="center" round="0" :isMaskClick="true" backgroundColor="transparent" @close="handleCloseModal">
		  <view class="distribution-contents">
		    <image 
		        :src="sheep.$url.cdn('/storage/default/20250419/24e0c5fcac58943520508d742c80cc9b.png')"
		        mode="widthFix" 
		        class="modal-image" />
		    <view class="cont">
		      <view class="title">铺货成功</view>
		      <view class="content">商品已铺货，您可到铺货记录查看</view>
		    </view>
		    <view class="btns">
		      <view class="btn go-on" @tap="handleCloseModal">继续铺货</view>
		      <view class="btn go-record" @tap="goDistributionRecord">去铺货记录</view>
		    </view>
		  </view>
		</su-popup>
	</s-layout>
</template>

<script setup>
	import sheep from '@/sheep';
  import assNavbar from '@/components/ass-navbar.vue';
	import ProductCard from './components/ProductCard.vue';
	import ProductSection from './components/ProductSection.vue'
	import { ref, reactive, computed } from 'vue'
	import { onLoad, onShow, onHide, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';

	import fuiActionsheet from "./components/fui-actionsheet.vue";
	
	const statusBarHeight = sheep.$platform.device.statusBarHeight; // 状态栏高度
	const searchRef = ref(null)
	const state = reactive({
		currentTab: 0,
		type: 'category',
		data: {
			list: [],
			src: "/storage/jd/20250412/5aba0435d9ca780c565c7d6167326a07.png",
			title: "鲸囍严选",
			url: "/pages/etc/category?id=3055"
		},
		style: {
			background: {
				bgColor: "#FFFFFF",
				bgImage: "",
				type: "color"
			}
		},

		keyword: '', // 搜索关键词
		quickList: [], // 快速出单好货
		hotList: [], // 站外爆款热销
		supplierList: [], // 严选供货商
		activeTab: 1,
		tabs: [
			{
				id: '',
				name: '综合排序',
			},
		],
		products: [],
		menuList: [
			{
				id: 1,
				name: '铺货记录',
				image: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250510/7f7cda40d64e87591ff63e4c7fbac987.png'
			},
			{
				id: 2,
				name: ` 收藏夹`,
				image: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250510/67fcc019935edd79e0a5b9ddf99842d1.png'
			},	
			{
				id: 3,
				name: '铺货设置',
				image: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250510/9afba9780eb18e4aef6b4a153c2dd380.png'
			}
		],
		menuShow: false,
		category_ids:'',
		navRetract: false,
		navOpacity: 1,
		classOpacity: 1,
		data: {},
		scrollTop:0,
		pages:0,
		list: [],
		tjList:[],
		more: 'more',
	
		classList:[],
		pagination: {
      current_page: 1,
      last_page: 1,
      total: 0,
    },
    loadStatus: '', // 加载更多状态 ['more' | 'noMore']
		showShort: false,
		sortType: '',
	})
	const typeList = [
		{ name: "销量从高到低", value: "sales" },
		{ name: "上新时间从近到远", value: "time" },
		{ name: "采购价从低到高", value: "price_1" },
		{ name: "采购价从高到低", value: "price_2" },
	]

	const showList = ref([]);

  let storeParams = reactive({
    page: 0,
    list_rows: 10, // 每页10条数据
    title: '', // 搜索关键字
    store_id: '', // 店铺id
		category_id: '',
		order_param: '' //  sales  time  price_1  price_2
  }) 

	const getSearchHeight = async () => {
		const query = uni.createSelectorQuery().in(this);
		query.select('.search-wrap').boundingClientRect(rect => {
			if (rect) {
				console.log('高度:', rect.height);
				state.searchHeight = rect.height

				console.log(state.searchHeight, 'state.searchHeight=')
			}
		}).exec();
	}


	const userInfo = computed(() => sheep.$store('user').userInfo);

	const onTabsChange = e => {
		console.log(e,'ee')
		if (e.id) {
			state.selecIndex = e.index;
			storeParams.category_id = e.id;
			storeParams.page = 0
			resetList()
			getShopSelectList()
		} else { // 综合排序
			showList.value = typeList.map(v => v.name)
			state.showShort = true
		}
		
	}

	const typeClick = (v) => {
		console.log(v, 'ooo')
		state.tabs[0].name = v.text
		state.sortType = typeList[v.index].value
		console.log(state.sortType, '排序id')
		storeParams.order_param = typeList[v.index].value
		state.selecIndex = 0;

		storeParams.category_id = ''
		
		storeParams.page = 0
		resetList()
		getShopSelectList()

		state.showShort = false
	}

	const handleMenuClick = (id) => {
		// 1=铺货记录 2=收藏夹 3=铺货设置
		if(id === 3){
			sheep.$router.go('/pages/distribution/setting')
		} else if (id === 2) {
			sheep.$router.go('/pages/distribution/collect')
		} else if (id === 1) {
			toRecord()
		}
		state.menuShow = false
	}
	const show = ref(false)
	const handleCloseModal = () => {
	  show.value = false
	}
	const goDistributionRecord = () => {
		toRecord()
	  handleCloseModal()
	}
	function toRecord(){
		uni.navigateTo({
			url:'/pages/distribution/record',
			events:{
				cancelRecord:function(e){
					state.products.some((product)=>{
						if(product.id == e.goods_id){
							product.is_in = 0
							return true
						}else{
							return false
						}
					})
					
				}
			}
		})
	}
	/**
	 * @description 跳转到列表页，携带数据
	 * @param type supplier=严选 hot=爆款 quick=快速出单
	 */
	const handleProductClick = (type) => {
		console.log(type, 'type')
		sheep.$router.go('/pages/distribution/list', {
			type
		})
	}
	const handleProductAction =async  (product) => {
		const res = await sheep.$api.distribution.addGoods(userInfo.value.cyq_store_id,product.id)
		if(res.error == 0){
			product.is_in = 1
			show.value = true
		} else {
			console.log('msg',res)
			uni.showToast({
				icon:'none',
				title:res.msg
			})
		}
	}
	const getClassList = async () => {
		const res = await sheep.$api.store.getStoreCategory()
		if (res.error == 0) {
			state.tabs = [
				{name:'综合排序',id:''},
				...res.data.children
			]
			
		}
	}

	const getShopSelectList = async () => {
		try {
			if(state.loadStatus == 'noMore'){
				return uni.showToast({
					title:'没有更多了',
					icon:'none'
				})
			}
			state.loadStatus = 'loading';
		
			const { error, data } = await sheep.$api.distribution.shopSelectList({
				...storeParams,
				store_id: userInfo.value.cyq_store_id,
				page: storeParams.page + 1
			})

			if (error == 0) {
				const { total, current_page, last_page ,per_page} = data
				storeParams.page = current_page
				state.products.push(...data.data)
				Object.assign(state.pagination, { total, current_page, last_page })

				if (per_page == data.data.length) {
				  state.loadStatus = 'more';
				} else {
				  state.loadStatus = 'noMore';
				}

				return data.data
			  }
		} catch (err) {
			console.log(err)
		}
		
	}

	const getCageData = () => {
		try {
			// 3325=严选 3324=爆款 3323=出单好货
			sheep.$api.distribution.shopSelectList({
				store_id: userInfo.value.cyq_store_id,
				category_id: '3325'
			}).then((res1)=>{
				if (res1.error == 0) {
					if (res1.data?.data.length > 2 ) {
						state.supplierList = res1.data?.data.slice(0, 2)
					} else {
						state.supplierList = res1.data?.data
					}
				}
			})
			 sheep.$api.distribution.shopSelectList({
				store_id: userInfo.value.cyq_store_id,
				category_id: '3324'
			}).then(res2=>{
				if (res2.error == 0) {
					if (res2.data?.data.length > 2 ) {
						state.hotList = res2.data?.data.slice(0, 2)
					} else {
						state.hotList = res2.data?.data
					}
				}
			})
			sheep.$api.distribution.shopSelectList({
				store_id: userInfo.value.cyq_store_id,
				category_id: '3323'
			}).then(res3=>{
				if (res3.error == 0) {
					if (res3.data?.data.length > 4 ) {
						state.quickList = res3.data?.data.slice(0, 4)
					} else {
						state.quickList = res3.data?.data
					}
				}
			})
			// console.log(res1, '品类严选===')
			// console.log(res2, '品类爆款===')
			// console.log(res3, '品类出单好货===')

			
			
			


			

			
		} catch (err) {
			console.log(err, 'err==')
		}
		
	}

	onLoad(async (opt) => {
		console.log(2222)
		
		await getClassList()
		getCageData()
		await getShopSelectList()
		await getSearchHeight()
	})

	onShow(() => {
		// getShopSelectList()
	})
	onReachBottom(()=>{
		loadmore()
	})
	
	onPullDownRefresh(() => {
		init()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		},300)
	})
	function search(){
		resetList()
		getShopSelectList()
	}
	async function loadmore(){
		await getShopSelectList()
	}
	async function init(){
		resetList()
		await getClassList()
		await getShopSelectList()
	}
	function resetList(){
		state.loadStatus= 'more'
		storeParams.page = 0
		state.products=[]
	}

</script>

<style lang="scss" scoped>
@import './style/index.scss';
</style>